package com.example.cyh.bczapp.Code.Activity;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cyh.bczapp.Code.BLL.RemenberBll;
import com.example.cyh.bczapp.Code.BLL.UserBLL;
import com.example.cyh.bczapp.Code.BLL.WordBLL;
import com.example.cyh.bczapp.Code.BLL.WordGroupBLL;
import com.example.cyh.bczapp.Code.Model.PlanInfEntity;
import com.example.cyh.bczapp.Code.Model.RemenberInfEntity;
import com.example.cyh.bczapp.Code.Model.UserInfEntity;
import com.example.cyh.bczapp.Code.Model.WordGroupInfEntity;
import com.example.cyh.bczapp.Code.Model.WordInfEntity;
import com.example.cyh.bczapp.R;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.Random;

public class RememberActivity extends Activity {
    private UserInfEntity user;
    private PlanInfEntity mainplan;
    private RemenberInfEntity reminf;
    private WordGroupInfEntity wg;
    //需要背的单词集合
    private ArrayList<String> remwordidlist;
    private ArrayList<String> reviewwordidlist;
    private ArrayList<WordInfEntity> wordinformation;
    private ArrayList<WordInfEntity> reviewinformation;

    //背单词
    private WordInfEntity rightword;
    private ArrayList<WordInfEntity> wlist;//错误单词信息3个
    private SimpleDraweeView rightpic;//记录正确图片的那个对象
    private ArrayList<SimpleDraweeView> listsd;//记录4个显示出来的图片对象
    private boolean show = false;
    private boolean review = false;//是否是复习
    private View.OnClickListener ChoseRight = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(RememberActivity.this, "选择正确", Toast.LENGTH_SHORT).show();
            if (!review) {//背单词状态
                wordinformation.remove(rightword);
                reviewinformation.add(rightword);
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                       RemenberBll  rb=new RemenberBll();
                       rb.Updatereminf("",String.valueOf(rightword.W_Id),String.valueOf(user.U_Id),mainplan.P_Id);
                   }
               }) .start();
            } else {//复习单词状态
                reviewinformation.remove(rightword);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        RemenberBll  rb=new RemenberBll();
                            rb.Updatereminf(String.valueOf(rightword.W_Id),"",String.valueOf(user.U_Id),mainplan.P_Id);
                    }
                }) .start();
            }
            WordinftoUi();
        }
    };
    private View.OnClickListener ChoseError = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(RememberActivity.this, "选择错误", Toast.LENGTH_SHORT).show();
        }
    };
    private Runnable Changeinf = new Runnable() {
        @Override
        public void run() {
            Changewordinf();
        }
    };
    ////////////临时变量
    SimpleDraweeView setcontrol;
    String picurl;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remember);
        user = (UserInfEntity) getIntent().getSerializableExtra("user");
        mainplan = (PlanInfEntity) getIntent().getSerializableExtra("plan");
        //点击事件
        findViewById(R.id.btnVoice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Playword();
            }
        });
        findViewById(R.id.btnDetail).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (show) {
                    findViewById(R.id.tvMeaning).setVisibility(View.INVISIBLE);
                    findViewById(R.id.tvHint).setVisibility(View.INVISIBLE);
                    show = false;
                } else {
                    findViewById(R.id.tvMeaning).setVisibility(View.VISIBLE);
                    findViewById(R.id.tvHint).setVisibility(View.VISIBLE);
                    show = true;
                }
            }
        });
        findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取集合信息
        Clearpic();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(mainplan==null)
                {
                    finish();
                    return;
                }
                RemenberBll re = new RemenberBll();
                //获取今天的背单词信息
                reminf = re.GetTodayRemember(mainplan.P_Id, String.valueOf(user.U_Id));
                WordGroupBLL wgb = new WordGroupBLL();
                //获取主要计划
                wg = wgb.getWordGroup(String.valueOf(mainplan.WG_id));
                Makelist();
                WordBLL wb = new WordBLL();
                reviewinformation = wb.GetWordInf(reviewwordidlist);
                wordinformation = wb.GetWordInf(remwordidlist);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Changewordinf();
                        if (wordinformation.size() != 0 && wordinformation != null)
                            WordinftoUi();
                    }
                });
            }
        }).start();
    }

    private void Makelist() {
        //处理需要背的单词
        ArrayList<String> all = new ArrayList<>();//单词组所有的单词
        for (String i : wg.WG_WordId.split(",")
                ) {
            all.add(i);
        }
        ArrayList<String> rem = new ArrayList<String>();//计划表中记录的已背单词
        if(mainplan.P_RemenberWord!=null)
        for (String i : mainplan.P_RemenberWord.split(",")
                ) {
            rem.add(i);
        }
        ArrayList<String> review = new ArrayList<String>();///计划表中记录需要复习的的单词
        if(mainplan.P_ReviewList!=null)
        for (String i : mainplan.P_ReviewList.split(",")
                ) {
            review.add(i);
        }
        ArrayList<String> tdrem = new ArrayList<String>();//今天的Remember表中的记录的数据  需要背的单词
        ArrayList<String> tdreview = new ArrayList<String>();///今天的Remember表中的记录的数据  需要复习的单词
        if (reminf.R_RWord != null) {
            for (String i : reminf.R_RWord.split(",")
                    ) {
                tdrem.add(i);
            }
            for (String i : reminf.R_EWord.split(",")
                    ) {
                tdreview.add(i);
            }
        }
        wordinformation = new ArrayList<WordInfEntity>();//需要背的新单词实体类集合
        reviewwordidlist = new ArrayList<String>();//需要复习的单词id集合
        remwordidlist = new ArrayList<String>();//当前需要背的单词id集合
        all.removeAll(rem);//和计划信息求交集
        //从单词组中取出一定量的单词id
        for (int i = 0; i < Integer.parseInt(mainplan.P_DayWork); i++) {
            remwordidlist.add(all.get(i));
        }
        /////计划表信息 -----背单词列表
        //去掉计划表中已经背过的单词
        for (String id : rem
                ) {
            remwordidlist.remove(id);
        }
        //去掉计划表中背了但是还需复习的单词
        for (String id : review) {
            remwordidlist.remove(id);
        }
        //////计划信息表 ------复习单词列表
        //加上需要复习的单词
        for (String id : review) {
            reviewwordidlist.add(id);
        }
        //////记录信息表 ------背单词列表
        //剪去记录信息表中今天已经背的单词
        for (String id : tdrem) {
            remwordidlist.remove(id);
        }
        //剪去记录信息表中今天已经背的单词但需要复习
        for (String id : tdreview) {
            remwordidlist.remove(id);
        }
        //////记录信息表 ------复习单词列表
        //加上今天需要复习的单词
        for (String id : tdreview) {
            reviewwordidlist.add(id);
        }
    }

    private void WordinftoUi() {
        if (review && reviewinformation.size() == 0) {
            Toast.makeText(RememberActivity.this, "已经完成了学习!", Toast.LENGTH_LONG).show();
            Changewordinf();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    UserBLL ub=new UserBLL();
                    ub.OverToday(String.valueOf(user.U_Id),user.U_PlanId);
                }
            }).start();
            return;
        }
        if (wordinformation.size() == 0&&!review) {
            review = true;
            Toast.makeText(RememberActivity.this, "开始复习", Toast.LENGTH_SHORT).show();
        }
        SetOtherWordInf();
        SetPic();
        runOnUiThread(Changeinf);
    }

    private SimpleDraweeView SetPic(int index, String url) {
        picurl = url;
        try {
            switch (index) {
                case 0:
                    setcontrol = ((SimpleDraweeView) findViewById(R.id.imgPic1));
                    break;
                case 1:
                    setcontrol = ((SimpleDraweeView) findViewById(R.id.imgPic2));
                    break;
                case 2:
                    setcontrol = ((SimpleDraweeView) findViewById(R.id.imgPic3));
                    break;
                case 3:
                    setcontrol = ((SimpleDraweeView) findViewById(R.id.imgPic4));
                    break;
                default:
                    setcontrol = null;
                    break;
            }
            if (setcontrol != null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setcontrol.setImageURI(picurl);
                    }
                });
            }
            return setcontrol;
        } catch (Exception ex) {
            Toast.makeText(RememberActivity.this, "设置图片时出错" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    private void Clearpic() {
        String picurl = "http://123.207.86.30/public/pic/20170525/2ec9a7a92487a92a32847baaa4a8761f.jpg";
        for (int i = 0; i < 4; i++) {
            SetPic(i, picurl);
        }
    }

    private void SetPic() {
        rightpic = null;
        if (listsd != null)
            listsd.clear();
        else
            listsd = new ArrayList<SimpleDraweeView>();///
        new Thread(new Runnable() {
            @Override
            public void run() {
                Random rd = new Random();//产生随机数
                ArrayList<WordInfEntity> listwrodinftmp = new ArrayList<WordInfEntity>();//临时用于记录没有使用的单词对象
                listwrodinftmp = new ArrayList<WordInfEntity>( review ? reviewinformation : wordinformation);
                int z = rd.nextInt(4);
                String ImagBaseurl = "http://123.207.86.30/public/pic/";
                rightpic = SetPic(z, ImagBaseurl + listwrodinftmp.get(0).W_PicPath);
                rightword = listwrodinftmp.get(0);
                Playword();
                listwrodinftmp.remove(listwrodinftmp.get(0));
                listsd.add(rightpic);
                final int right = z;
                try {
                    WordInfEntity last = new WordInfEntity();
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Random rd = new Random();//产生随机数
//                            ArrayList<String> all = new ArrayList<>();//单词组所有的单词
//                            for (String i : wg.WG_WordId.split(",")
//                                    ) {
//                                all.add(i);
//                            }
//                            ArrayList<String>  listid=new  ArrayList<String>();
//                            for (int i=0;i<3;i++)
//                            {
//                                String  id=all.get(rd.nextInt(all.size()));
//                                listid.add(id);
//                            }
//                            WordBLL  wb=new WordBLL();
//                            wlist= wb.GetWordInf(listid);
//                            handler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    for (int i=0,j=0;i<3;i++)
//                                    {
//                                        if (i == right) {
//                                            continue;
//                                        }
//                                        else {
//                                            SetPic(i, "http://123.207.86.30/public/pic/" + wlist.get(j).W_PicPath);
//                                            j++;
//                                        }
//                                    }
//                                }
//                            });
//                        }
//                    }).start();

                    for (int i = 0; i < 4; i++) {
                        if (i == right)
                            continue;
                        if (listwrodinftmp.size() != 0) {
                            int y = rd.nextInt(listwrodinftmp.size());
                            listsd.add(SetPic(i, ImagBaseurl + listwrodinftmp.get(y).W_PicPath));
                            last = listwrodinftmp.get(y);
                            listwrodinftmp.remove(listwrodinftmp.get(y));
                        } else
                            listsd.add(SetPic(i, ImagBaseurl + last.W_PicPath));
                    }
                } catch (Exception ex) {
                    Toast.makeText(RememberActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        rightpic.setOnClickListener(ChoseRight);
                        for (SimpleDraweeView sv : listsd
                                ) {
                            if (sv.equals(rightpic))
                                continue;
                            sv.setOnClickListener(ChoseError);
                        }
                    }
                });
            }
        }).start();
    }

    private void SetOtherWordInf() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!review) {
                    ((TextView) findViewById(R.id.tvWord)).setText(wordinformation.get(0).W_Name);
                    ((TextView) findViewById(R.id.tvMeaning)).setText(wordinformation.get(0).W_Chinese);
                    ((TextView) findViewById(R.id.tvHint)).setText(wordinformation.get(0).W_CExSentence);
                    ((TextView) findViewById(R.id.tvExampleSentence)).setText(wordinformation.get(0).W_ExSentence);
                    ((TextView) findViewById(R.id.tvPhonetic)).setText(wordinformation.get(0).W_SoundMark);
                } else {
                    ((TextView) findViewById(R.id.tvWord)).setText(reviewinformation.get(0).W_Name);
                    ((TextView) findViewById(R.id.tvMeaning)).setText(reviewinformation.get(0).W_Chinese);
                    ((TextView) findViewById(R.id.tvHint)).setText(reviewinformation.get(0).W_CExSentence);
                    ((TextView) findViewById(R.id.tvExampleSentence)).setText(reviewinformation.get(0).W_ExSentence);
                    ((TextView) findViewById(R.id.tvPhonetic)).setText(reviewinformation.get(0).W_SoundMark);
                }
            }
        });
    }

    private void Playword() {
        try {
            MediaPlayer player = new MediaPlayer();
            player.setDataSource("http://123.207.86.30/public/mp3/" + rightword.W_VoicePath);
            player.prepare();
            player.start();
        } catch (Exception ex) {
        }

    }

    private void Changewordinf() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (wordinformation.size() >= Integer.parseInt(mainplan.P_DayWork))
                    ((TextView) findViewById(R.id.tvShouldNewWord)).setText(mainplan.P_DayWork);
                else
                    ((TextView) findViewById(R.id.tvShouldNewWord)).setText(String.valueOf(wordinformation.size()));
                ((TextView) findViewById(R.id.tvReciteWord)).setText(String.valueOf(reviewinformation.size()));
            }
        });
    }
}